<template>
<div class="com-container">
	<div class="com-chart" ref="stockRef" id="stockRef"  @mouseover="mousover" @mouseout="mousout"></div>
</div>
</template>
<script lang='ts' setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue';

import * as echarts from 'echarts'
import '../../public/theme/chalk'
import socketService from '../api/socket_sever'
import {getstock} from '../api/api'
import { useStore } from 'vuex';
const store = useStore()
  const stockRef = ref()
  const comStyle = computed( () => {
				return {
					fontSize: state.titleFontSize + 'px'
				}
			})
	const state = reactive<{
    // myChart: echarts.ECharts | null,
    data: API.Stock[]
    currentPage: number
    totalPage: number
    setinter: number
    currentindex: number
    catName:string
    titleFontSize: number
	}>({
    // myChart: null,
    data: [],// 服务器返回数据
    currentPage: 0,// 第几多少页
    totalPage: 0, // 一共多少页
    setinter: 0,
    currentindex: 0,
    catName: '',
    titleFontSize: 0
	})
  let myChart: echarts.ECharts | null = null
	onMounted(async() => {
      await initexs()
      screenAdapter()
      window.addEventListener('resize',screenAdapter )
	})
  onUnmounted(() => {
    clearInterval(state.setinter)
    socketService.Instance.unRegisterCallBack('stock')
    window.removeEventListener('resize', screenAdapter)
  })
  // 初始化exs
  const initexs = async () => {
    var chartDom = document.getElementById('stockRef');
    myChart = echarts.init(chartDom as HTMLElement, store.state.theme)
    const initoption = {
      title: {
        text: '▎库存与销量分析',
        left: 20,
        top: 20
      },
      // legend: {
      //   top: '5%',
      //   right: '5%',
      //   icon: 'circle'
      // },
      series: [
        {
          type: 'pie'
        }
      ]
    }
    initoption && (myChart as  echarts.ECharts).setOption(initoption);
    socketService.Instance.registerCallBack('stock', getData)
    try {
      await getstock()
    } catch (error) {
      console.log(error);
    }
  }
    // 获取数据
  const getData = (data: API.Stock[]) => {
    state.data = data
    updataChar()
    setIn()
  }
    // 更新图表
  const updataChar = () => {
    const centerArr = [
					['18%', '40%'],
					['50%', '40%'],
					['82%', '40%'],
					['34%', '75%'],
					['66%', '75%']
				];
        const colorArr = [
					['#4FF778', '#0BA82C'],
					['#E5DD45', '#E8B11C'],
					['#E8821C', '#E55445'],
					['#5052EE', '#AB6EE5'],
					['#23E5E5', '#2E72BF']
				];
    const stare = state.currentindex * 5
    const end = (state.currentindex + 1) * 5
    const showdata = state.data.slice(stare, end)
    const seriesdata = showdata.map((item, index) => {
      return {
        type: 'pie',
        name: item.name,
        center: centerArr[index],
        hoverAnimation: false,
        labelLine: {
          show: false
        },
        label: {
          position: 'center',
            color:colorArr[index][0]
        },
        data: [{
          value: item.sales,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              { offset: 0, color: colorArr[index][0] },
              { offset: 1, color: colorArr[index][1] }
            ])
          }
        }, {
          name: item.name + '\n' + item.sales,
          value: item.stock,
          itemStyle: {
            color: '#333843'
          }
        }]
      }
    })
    const dataoption = {
      series: seriesdata,
    }
    dataoption && (myChart as  echarts.ECharts).setOption(dataoption);
    screenAdapter()
  }
  const screenAdapter = () => {
    state.titleFontSize = stockRef.value.offsetWidth / 100 * 3.6;
    const innerradius = state.titleFontSize * 2
    const outradius = innerradius * 1.125
    // console.log(titleFontSize);
    const Adapteroption = {
      title: {
        textStyle: {
          fontSize: state.titleFontSize / 2
        }
      },
      series:[ 
        {
          radius: [outradius, innerradius],
          label: {
            fontSize: state.titleFontSize / 2
          }
        },
        {
          radius: [outradius, innerradius],
          label: {
            fontSize: state.titleFontSize / 2
          }
        },
        {
          radius: [outradius, innerradius],
          label: {
            fontSize: state.titleFontSize / 2
          }
        },
        {
          radius: [outradius, innerradius],
          label: {
            fontSize: state.titleFontSize / 2
          }
        },
        {
          radius: [outradius, innerradius],
          label: {
            fontSize: state.titleFontSize / 2
          }
        },
      ],
    }
    Adapteroption && (myChart as  echarts.ECharts).setOption(Adapteroption);
    (myChart as  echarts.ECharts).resize()
  }
  const setIn = () => {
    if (state.setinter) {
      clearInterval(state.setinter)
    }
    state.setinter = setInterval(() => {
      state.currentindex === 1 ? state.currentindex = 0 : state.currentindex = 1
      updataChar()
    }, 2000)
  }
  const mousover = () => {
    clearInterval(state.setinter)
  }
  const mousout = () => {
    setIn()
  }
  defineExpose({
    screenAdapter
  })
  watch ( () => store.state.theme, async() => {
    // console.log('qweqwe');
    (myChart as echarts.ECharts).dispose();
    await initexs()
    screenAdapter()
    updataChar()
  }, {
    // immediate: true, // 是否初始化立即执行一次, 默认是false
    deep: true // 是否是深度监视, 默认是false
  })
</script>
<style lang='less' scoped>
</style>